if (window.plus) {
    ready();
} else {
    document.addEventListener('plusready', ready, false);
}
$(function() {
    if (AGENT_CLIENT.WEB) {
        ready();
    }
})

function ready() {
    var uploadControl = null,
        thisPage = null,
        user = null,
        html = [];
    var accountPage = function() {
        this.init();
    };
    accountPage.prototype = {
        init: function() {
            try {
                this.initData();
                this.bindEvent();
            } catch (e) {
                $.toast(e.message);
            }
        },
        initData: function() {
            user = getLocalStorage(STORAGE_MANAGER.user);
            if (user && user.id > 0) {
                $.ajax({
                    url: CONFIG_MANAGER.RequstUrl + "v1/member/" + user.id,
                    type: "GET",
                    async: true,
                    headers: {
                        "token": user.token
                    },
                    beforeSend: function() {
                        $.showWaiting('等待中...');
                    }
                }).done(function(data) {
                    //加载数据
                    thisPage.loadPersonalMsg(data);
                }).fail(function() {
                    $.alert("你的帐号已经在其他地方登录", function() {
                        clearLocalStorage();
                        redirect("../account/login.html?backurl=account.html");
                        return;
                    });
                }).always(function() {
                    $.closeWaiting();
                });
            } else {
                redirect("login.html");
                return false;
            }
        },
        loadPersonalMsg: function(data) {
            html = [];
            html.push('<div class="wlxqbg">');
            html.push('<div class="wlxqnrbg mbtopbottom" style="border:none">');
            html.push('<p id="uploadAvatar" style="position: relative;" class="wlxqnr mbbottom">');
            html.push('<span>');
            if (AGENT_CLIENT.WEB) {
                html.push('<input id="avatarFile" class="a_upload" type="file" capture="camera" accept="image/png,image/gif,image/jpg,image/jpeg">');
            }
            html.push('<b class="grzlxtx">');
            var avatar = ("" == data.avatar) ? "../../images/avatar-male.png" : getImageUrl(data.avatar, 30, 30);
            html.push('<img id="userAvatar" src="' + avatar + '" /></b>');
            html.push('<i class="iconfont icon-jiantou2"></i>')
            html.push('</span>');
            html.push('头像</p>');
            html.push('<p id="nick" style="position:relative;" class="wlxqnr mbbottom"><span><b class="ybzt">' + data.nickname + '</b><i class="iconfont icon-jiantou2"></i></span>昵称</p>');
            html.push('<p id="phone" class="wlxqnr mbbottom"><span><b class="ybzt">' + ((data.phone == '') ? '绑定' : data.phone) + '</b><i class="iconfont icon-jiantou2"></i></span>手机号码</p>');
            html.push('</div>');
            html.push('<div class="wlxqnrbg mbtopbottom" style="border:none">');
            html.push('<p id="password" class="wlxqnr mbbottom"><span><b class="ybzt"></b><i class="iconfont icon-jiantou2"></i>\</span>密码</p>');
            html.push('<p id="address" class="wlxqnr mbbottom"><span><b class="ybzt"></b><i class="iconfont icon-jiantou2"></i></span>收货地址</p>');
            html.push('</div>');
            html.push('</div>');
            $("#main").html(html.join(''));
            //修改昵称
            $("#main").on("click", "#nick", function() {
                redirect("editnick.html?nickname=" + data.nickname);
                return false;
            });
            //点击手机号
            $("#main").on("click", "#phone", function() {
            	//修改手机号
                if (data.phone) {
                    redirect("editphone.html?phone=" + data.phone + "&backurl=account|account.html");
                    return false;
                } 
                //绑定手机号
                else {
                    redirect("setphone.html?backurl=account|account.html");
                    return false;
                }
            });
            //点击跳转选择修改密码的类型，登陆密码或者支付密码
            $("#main").on("click", "#password", function() {
                if (data.is_phone || data.phone) {
                    redirect("selectPasstype.html?phone=" + data.phone);
                    return false;
                } else {
                	//未设置手机号
                  $.alert("请先绑定手机号", function(e) {
                      redirect("setphone.html?backurl=account|account.html");
                  });
                }
            });
            $("#main").on("click", "#address", function() {
                redirect("address.html");
                return false;
            });
            //app上加载图片上传控件
            if (AGENT_CLIENT.APP) {
                uploadControl = new uploadPage();
            }
        },
        bindEvent: function() {
            //点击回退
            $("#back").on("click", function() {
                if (AGENT_CLIENT.APP) {
                    plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
                    plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");
                } else {
                    redirect("../mine/mylife.html");
                }
            });
            //上传个人图像
            this.bindUploadAvatar();
        },
        bindUploadAvatar: function() {
            //app上传头像
            if (AGENT_CLIENT.APP) {
                //点击头像弹出蒙板
                $("#main").on("click", "#uploadAvatar", function() {
                    uploadControl.show();
                });
                //拍照
                $("#main").on("click", "#uploadFromCamera", function(e) {
                    thisPage.getImageCamera();
                });
                //从相册中选择
                $("#main").on("click", "#uploadFromAlbums", function(e) {
                    thisPage.getImageAlbum();
                });
            }
            //wap端上传图像
            else {
                //上传头像
                $("#main").on("change", "#avatarFile", function() {
                    var that = $(this);
                    thisPage.uploadPersonAvatar($(that)[0].files[0]);
                });
            }
        },
        getImageAlbum: function() {
            plus.gallery.pick(function(path) {
                thisPage.uploadPersonAvatar(path);
            }, function(e) {
                console.log(e);
            }, {
                filter: "image"
            });
        },
        getImageCamera: function() {
            var cmr = plus.camera.getCamera(1);
            if (null == cmr) {
                $.toast("没有找到摄像头");
            } else {
                cmr.captureImage(function(p) {
                    plus.io.resolveLocalFileSystemURL(p, function(entry) {
                        var path = "file://" + entry.fullPath;
                        thisPage.uploadPersonAvatar(path);
                    }, function(e) {
                        $.toast(e.message);
                    });
                }, function(e) {}, {
                    filename: "_doc/camera/"
                });
            }
        },
        uploadPersonAvatar: function(path) {
            lrz(path, {
                quality: 0.7,
                done: function(result) {
                    var index = result.base64.indexOf(',');
                    var newStrings = result.base64.substr(index + 1);
                    var requestData = {
                        content: newStrings
                    };
                    $.ajax({
                        type: "POST",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/uploadavatar/" + user.id,
                        async: true,
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        headers: {
                            "token": user.token
                        },
                        beforeSend: function() {
                            $.showWaiting();
                        }
                    }).done(function(data) {
                        var src = getImageUrl(data.avatar, 30, 30);
                        $("#userAvatar").attr("src", src);
                    }).fail(function(data) {
                        console.log(data);
                    }).always(function() {
                        if (AGENT_CLIENT.APP) {
                            uploadControl.hide();
                        }
                        $.closeWaiting();
                    });
                }
            });
        }
    };
    thisPage = new accountPage();
}